package cn.yunhe.control;

import cn.yunhe.server.UserServer;
import cn.yunhe.util.DateUtil;
import cn.yunhe.entity.Blank;
import cn.yunhe.entity.Topic;
import cn.yunhe.entity.User;
import cn.yunhe.server.TopicServer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;


@WebServlet("/PostTopicServlet")
public class PostTopicServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取文本标题和内容
        String title = request.getParameter("title");
        String context = request.getParameter("context");
        //获取板块信息
        String bId = request.getParameter("bId");
        String bName = request.getParameter("bName");
        Blank blank = new Blank(Integer.parseInt(bId),bName); //获取板块对象
        //获取用户信息
        HttpSession session = request.getSession(); //获取session对象
        String username = (String) session.getAttribute("username");
        String password = (String) session.getAttribute("password");
        User user = new User(username,password); //新建用户对象
        UserServer userServer = new UserServer();
        User user1 = userServer.getUserByUnamePwd(user);  //获取用户对象全部信息

        Date date = new Date(); //获取日期对象
        String strDate = DateUtil.date2StringDateTime(date); //将日期转化成字符串
        TopicServer topicServer = new TopicServer();
        //获取帖子对象
        Topic topic = new Topic(title,context,strDate,user1,blank);
        boolean flag = topicServer.PostTopic(topic); //执行帖子发布方法,定义变量接收发帖结果
        if (flag){
            request.setAttribute("result","帖子发布成功!!");
            request.getRequestDispatcher("addTopicOnblank.jsp").forward(request,response);
        }else {
            request.setAttribute("result","帖子发布失败,帖子标题重复,请修改发帖标题 !!");
            request.getRequestDispatcher("addTopicOnblank.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
